﻿using System.Runtime.InteropServices;
using UnityEngine;

public class NavMeshInterface
{
    [DllImport("RecastLibrary")]
    public extern static int LoadFromFile(string pathFilename, int maxNodes, float[] extents, float[] wideExtents);

    [DllImport("RecastLibrary")]
    public extern static int LoadFromData(byte[] dataByteArray, int length, int maxNodes, float[] extents, float[] wideExtents);

    [DllImport("RecastLibrary")]
    public extern static int FindStraightPath(int navMeshId, float x1, float y1, float z1, float x2, float y2, float z2, float[] resultPath, int maxPathSize);

    [DllImport("RecastLibrary")]
    public extern static bool GetPolyHeight(int navMeshId, float x, float y, float z, ref float height);

    [DllImport("RecastLibrary")]
    public extern static bool FindNearestPoly(int navMeshId, float x, float y, float z, bool useWideExtents, float[] resultPoint);

    [DllImport("RecastLibrary")]
    public extern static bool Raycast(int navMeshId, float x1, float y1, float z1, float x2, float y2, float z2);

    [DllImport("RecastLibrary")]
    public extern static bool MoveAlongSurface(int navMeshId, float x1, float y1, float z1, float x2, float y2, float z2, float[] resultPoint);

    [DllImport("RecastLibrary")]
    public extern static void Release(int navMeshId);

    private static float epsilon = 0.01f;
    private static int maxNodes = 1024;
    private static float[] extents = { 1.0f, 1.0f, 1.0f };
    private static float[] wideExtents = { 10.0f, 10.0f, 10.0f };

    public static int LoadFromFile(string pathFilename)
    {
        return LoadFromFile(pathFilename, maxNodes, extents, wideExtents);
    }

    public static int LoadFromData(byte[] dataByteArray, int length)
    {
        return LoadFromData(dataByteArray, length, maxNodes, extents, wideExtents);
    }

    public static bool IsWalkable(int navMeshId, Vector3 point)
    {
        float[] resultArray = new float[3];
        if (FindNearestPoly(navMeshId, point.x, point.y, point.z, false, resultArray))
        {
            Vector3 resultPoint = new Vector3(resultArray[0], 0.0f, resultArray[2]);
            point.y = 0.0f;
            float distance = Vector3.Distance(resultPoint, point);
            if (distance < epsilon)
            {
                return true;
            }
        }

        return false;
    }
}
